﻿/******************************************************   
创建者: ljj
创建时间: 2018-07-17
修改:
修改时间: 
功能: 微信
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.kmer;
using com.kmer.ApiServer;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using TouchUIWeiXinAPI.common;
using com.kmer.db;
using com.kmer.Helper;
using com.kmer.library.Helper;
using TouchUIWeiXinAPI.model;

namespace TouchUIWeiXinAPI
{
    /// <summary>
    /// 微信小程序获取openid,校验账号，创建账号，生成权限
    /// </summary>
    public class WXLoginHandler : WXBaseHandler
    {
        /// writer:ljj
        /// Create Date：2018-07-17
        [Description("校验此微信用户是否存在")]
        [ReturnType(typeof(WXModel.LoginModel))]
        public ApiResult CheckWxUser([ParamDescription("code")] string code,
            [ParamDescription("是否企业微信")] bool Iswxwork = false)
        {
            try
            {
                Log.Error("code:" + code);
                //var accessToken = AccessTokenContainer.TryGetToken(WxProgramConfit.AppId, WxWorkConfig.ContactsSecret);
                //JsApiTicketContainer.Register(WxWorkConfig.CorpId, WxWorkConfig.ContactsSecret); WxProgramConfit

                // var user = OAuth2Api.GetUserId(accessToken, Code);
                //TODO:获取OpenId,session_key
                if (Iswxwork)
                {
                    var token = WXQiYeHelper.GetWXAccessToken();
                    if (token.errcode == "0")
                    {
                        var sessionKey = WXQiYeHelper.GetWXSessionKey(code, token.access_token);
                        if (sessionKey.errcode == "0")
                        {
                            var dc = new km_platformEntities();
                            var query = dc.t_order_wx_account.FirstOrDefault(
                                d => d.OpenId == sessionKey.userid && !d.IsRemove && d.Iswxwork == Iswxwork);
                            if (query != null)
                            {
                                if (query.IsDisable) return Error("该用户已被禁用!");
                                var orderHandler = new WXOrderHandler();
                                var goingOrder = orderHandler.GetGoingOrder(dc);
                                var allOrder = orderHandler.GetAllOrder(dc);
                                var toPart = orderHandler.GetToPart(dc, query.OpenId);
                                var user = new WXModel.LoginModel
                                {
                                    OpenId = query.OpenId,
                                    NickName = query.NickName,
                                    AccountType = query.AccountType,
                                    goingOrderList = goingOrder,
                                    AllOrder = allOrder,
                                    ToPart = toPart,
                                };
                                return Success(user);
                            }
                            return Error($"[{sessionKey.userid}]该用户不存在!");
                        }
                        return Error(sessionKey.errmsg);
                    }
                    return Error(token.errmsg);
                }
                else
                {
                    var result = Senparc.Weixin.WxOpen.AdvancedAPIs.Sns.SnsApi.JsCode2Json(WxProgramConfit.AppId,
                        WxProgramConfit.AppSecret,
                        code);
                    if (result.errcode == 0)
                    {
                        //result.openid;result.session_key;
                        var dc = new km_platformEntities();
                        var query = dc.t_order_wx_account.FirstOrDefault(
                            d => d.OpenId == result.openid && !d.IsRemove &&
                                 (!d.Iswxwork.HasValue || d.Iswxwork == Iswxwork));
                        if (query != null)
                        {
                            if (query.IsDisable) return Error("该用户已被禁用!");
                            var orderHandler = new WXOrderHandler();
                            var goingOrder = orderHandler.GetGoingOrder(dc);
                            var allOrder = orderHandler.GetAllOrder(dc);
                            var toPart = orderHandler.GetToPart(dc, query.OpenId);
                            var user = new WXModel.LoginModel
                            {
                                OpenId = query.OpenId,
                                NickName = query.NickName,
                                AccountType = query.AccountType,
                                goingOrderList = goingOrder,
                                AllOrder = allOrder,
                                ToPart = toPart,
                            };
                            return Success(user);
                        }
                        return Error($"[{result.openid}]该用户不存在!");
                    }
                    //TODO: 校验账号信息
                    return Error(result.errmsg);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }

        /// writer:ljj
        /// Create Date：2018-07-17
        [Description("注册")]
        [ReturnType(typeof(WXModel.LoginModel))]
        public ApiResult Register([ParamDescription("二维码信息")] string Json, [ParamDescription("OpenId")] string OpenId,
            [ParamDescription("微信昵称")] string NickName, [ParamDescription("是否企业微信")] bool Iswxwork = false)
        {
            try
            {
                if (string.IsNullOrEmpty(Json)) return Error("二维码无信息!");
                if (string.IsNullOrEmpty(OpenId)) return Error("OpenID不能为空!");
                var query = Json.FromJson<WXModel.CodeModel>();
                var dc = new km_platformEntities();
                if (dc.t_order_wx_account.Any(d => d.CheckCode == query.CheckCode)) return Error("该二维码已失效!");
                if (!dc.t_order_wx_account.Any(d => d.OpenId == query.SourceOpenId && d.AccountType == 0 &&
                                                    !d.IsDisable && !d.IsRemove)) return Error("该管理员不存在!");
                if (dc.t_order_wx_account.Any(d => d.OpenId == OpenId || d.SourceOpenId == OpenId && !d.IsRemove))
                    return Error("该用户已存在!");
                var user = new t_order_wx_account
                {
                    OpenId = OpenId,
                    NickName = NickName,
                    SourceOpenId = query.SourceOpenId,
                    AccountType = query.AccountType,
                    CheckCode = query.CheckCode,
                    CreateDate = DateTime.Now,
                    ScoreRate = 1,
                    IsDisable = false,
                    IsRemove = false,
                    Iswxwork = Iswxwork
                };
                dc.t_order_wx_account.Add(user);
                var orderHandler = new WXOrderHandler();
                var goingOrder = orderHandler.GetGoingOrder(dc);
                var allOrder = orderHandler.GetAllOrder(dc);
                var toPart = orderHandler.GetToPart(dc, user.OpenId);
                var result = new WXModel.LoginModel
                {
                    OpenId = user.OpenId,
                    NickName = user.NickName,
                    AccountType = query.AccountType,
                    goingOrderList = goingOrder,
                    AllOrder = allOrder,
                    ToPart = toPart,
                };
                dc.SaveChanges();
                return Success(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }
        
        /// writer:ljj
        /// Create Date：2018-07-18
        [Description("权限列表")]
        [ReturnType(typeof(IList<WXModel.UserModel>))]
        public ApiResult AccountList([ParamDescription("OpenId")] string OpenId, [ParamDescription("是否企业微信")] bool Iswxwork = false)
        {
            try
            {
                if (string.IsNullOrEmpty(OpenId)) return Error("OpenID为空!");
                var dc = new km_platformEntities();
                if (!dc.t_order_wx_account.Any(d => d.OpenId == OpenId &&
                                                    (!d.Iswxwork.HasValue || d.Iswxwork == Iswxwork) && !d.IsDisable &&
                                                    !d.IsRemove && d.AccountType == 0)) return Error("该用户没有管理权限!");
                var query = dc.t_order_wx_account.Where(d => !d.IsRemove).Select(d => new WXModel.UserModel
                {
                    OpenId = d.OpenId,
                    NickName = string.IsNullOrEmpty(d.AliasName) ? d.NickName : d.AliasName,
                    ScoreRate = d.ScoreRate,
                    AccountType = d.AccountType,
                    IsDisable = d.IsDisable,
                    IsRemove = d.IsRemove,
                    Iswxwork = d.Iswxwork ?? false,
                }).ToList();
                return Success(query);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }
        
        /// writer:ljj
        /// Create Date：2018-07-17
        //[MustAdmin]
        [JsonType]
        [Description("更改权限")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult ModifyAccount([ParamDescription("账号类型")] WXModel.ModifyModel param)
        {
            try
            {
                if (param == null) return Error("参数对象为空!");
                if (string.IsNullOrEmpty(param.SourceOpenId)) return Error("OpenID为空!");
                var dc = new km_platformEntities();
                if (!dc.t_order_wx_account.Any(d => d.OpenId == param.SourceOpenId && !d.IsDisable && !d.IsRemove &&
                                                    d.AccountType == 0)) return Error("该用户没有管理权限!");
                if (param.userList != null)
                {
                    foreach (var item in param.userList)
                    {
                        var query = dc.t_order_wx_account.FirstOrDefault(d => d.OpenId == item.OpenId);
                        if (query != null)
                        {
                            query.AliasName = item.NickName;
                            query.ScoreRate = item.ScoreRate;
                            query.AccountType = item.AccountType;
                            query.IsDisable = item.IsDisable;
                            query.IsRemove = item.IsRemove;
                        }
                    }
                    dc.SaveChanges();
                }
                return Success(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }
    }
}
